import { computed, toRaw, ref, reactive, nextTick } from 'vue'
import { Store } from 'vuex'
import { MessageFunc } from '@/utils/ElMessageFunc'
import { AllStateType, attrValsProps } from '@/store/storeType'

export const defaultParams = {
  activeName: ref<'many' | 'only'>('many'), // 动态参数和静态属性的变量
  handleChangeVal: ref(), // 保存选择的cat_id值的变量
  tableData: ref<attrValsProps[]>(), // table 表格数据的变量
  inputStateArr: ref<{inputVisible: boolean, inputValue: string}[]>([]), // input框状态集合
  input_Vals: reactive<{[key: number]: string[]}>({}), // 标签栏数据集合
  compileForm: reactive({ name: '' }), // 对话框Input框
  manyForm: reactive({ name: '' }), // dialog 弹框form表单数据
  saveTagInput: ref<HTMLInputElement>() // input框Dom节点的绑定变量
}

export const categoriesClickEvent = (store: Store<AllStateType>) => {
  const { activeName, handleChangeVal, tableData, inputStateArr, input_Vals } = defaultParams
  const handleChange = (val: any) => { // 选中之后的点击事件
    if (!val) { // 清空选择框
      val = ''
      return
    }
    handleChangeVal.value = val[2]
    store.dispatch('getIdCategories', { cid: val[2], sel: activeName.value }).then(() => {
      tableData.value = store.getters.CategorieToId(val[2], activeName.value)
      if (inputStateArr.value.length !== 0) inputStateArr.value = []
      tableData.value?.forEach((item: any) => {
        inputStateArr.value.push({inputVisible: false,inputValue: ''});
        input_Vals[item.attr_id as number] = toRaw(item).attr_vals as string[]
      })
    })
  }

  const isBtnDisabled = computed(() => !handleChangeVal.value) // 按钮显示与隐藏

  return { handleChange, isBtnDisabled }
}

export const DialogStateFn = (store: Store<AllStateType>) => {
  const { activeName, handleChangeVal, tableData, input_Vals, compileForm, manyForm, inputStateArr } = defaultParams
  // 编辑对话框
  const compileDialogData = reactive({
    dialogVisible: false,// 对话框关闭打开
    handleClose () {// 右上角x
      compileDialogData.dialogVisible = false
    },
    compileAttr_id: 0,// 当前商品id
    compileIndex: 0,//当前编辑栏下标
    // 确定按钮更新内容
    dialogUpLoadClick () {
      compileDialogData.dialogVisible = false
      store.dispatch('putIdCategories', {
        cateId: handleChangeVal.value,
        attr_id: compileDialogData.compileAttr_id,
        data: {
          attr_name: compileForm.name,
          attr_sel: activeName.value,
          attr_vals: (input_Vals[compileDialogData.compileAttr_id])?.join(',')
        }
      }).then(res => {
        if (res.status !== 200) {
          MessageFunc('error', '编辑失败')
          return
        }
        const { data } = res.data;
        (tableData.value as attrValsProps[])[compileDialogData.compileIndex] = data
        MessageFunc('success', '编辑成功')
        compileForm.name = ''
      })
    }
  })

  // dialog 弹出框各种数据 添加参数对话框
  const dialogData = reactive({
    dialogVisible: false,
    dialogTitle: '动态参数',
    handleDialogUpLoad () { // 添加确定按钮，发送事件
      dialogData.dialogVisible = false
      store.dispatch('postAddAttributes', {
        cat_id: handleChangeVal.value,
        data: {
          attr_name: manyForm.name,
          attr_sel: activeName.value,
          attr_vals: "test"
        }
      }).then((res: any) => {
        if (res.status !== 200) return
        const { data } = res.data
        tableData.value = [...tableData.value as attrValsProps[], data]
        inputStateArr.value.push({inputVisible: false,inputValue: ''})
        input_Vals[data.attr_id as number] = (toRaw(data).attr_vals as string).split(' ') as string[]
        MessageFunc('success', '添加成功')
        manyForm.name = ''
      })
    },
    handleDialogClose () {
      dialogData.dialogVisible = false
    }
  })

  return { compileDialogData, dialogData }
}

export const operationBtns = (store: Store<AllStateType>, compileDialogData: any) => {
  const { compileForm, handleChangeVal, activeName, tableData } = defaultParams
  // 商品编辑按钮
  const handleEdit = (index: any, row: any) => {
    compileForm.name = row.attr_name
    compileDialogData.compileAttr_id = row.attr_id
    compileDialogData.compileIndex = index
    compileDialogData.dialogVisible = true
  }
  // 商品删除按钮
  const handleDelete = (row: any) => {
    store.dispatch('categorieDelete', { attr_id: row.attr_id, attr_sel: row.attr_sel, cat_id: row.cat_id }).then(() => {
      tableData.value = store.getters.CategorieToId(handleChangeVal.value, activeName.value)
      MessageFunc('success', '删除成功')
    }).catch(() => {
      MessageFunc('error', '删除失败')
    })
  }

  return { handleEdit, handleDelete }
}

export const tableTagsInputEventsAndParamsAndObj = (store: Store<AllStateType>, dialogData: any) => {
  const { handleChangeVal, input_Vals, inputStateArr, saveTagInput, activeName, tableData } = defaultParams
  const tagInputObj = reactive({ // 表格扩展框相关数据
    handleClose: (tag: string, $index: number, row: any) => { // tag删除事件
      console.log(input_Vals[row.attr_id], '删除前')
      input_Vals[row.attr_id] = (input_Vals[row.attr_id]?.filter(item => {
        if (item !== tag) return item
      }))
      console.log((input_Vals[row.attr_id]?.filter(item => {
        if (item !== tag) return item
      })), '删除后')

      input_Vals[row.attr_id] ? MessageFunc('success', '删除成功') : MessageFunc('error', '最后一个了，不能全部删除掉哦！')

      store.dispatch('putIdCategories', { // 更新tag数据
        cateId: handleChangeVal.value,
        attr_id: row.attr_id,
        data: {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: (input_Vals[row.attr_id] as string[])?.join(',')
        }
      })
    },
    handleInputConfirm: (rowData: attrValsProps, $index: number) => { // 输入框失去焦点事件
      const inputState = inputStateArr.value[$index]
      const input_vals = input_Vals[rowData.attr_id as number]

      if (inputState.inputValue?.trim().length === 0) {
        inputState.inputValue = '',
        inputState.inputVisible = false
        return
      }
      inputState.inputVisible = false; // 关闭

      
      input_Vals[rowData.attr_id as number] = [...input_vals, (inputState.inputValue as string).trim()]

      store.dispatch('putIdCategories', { // 更新vals
        cateId: handleChangeVal.value,
        attr_id: rowData.attr_id,
        data: {
          attr_name: rowData.attr_name,
          attr_sel: rowData.attr_sel,
          attr_vals: (input_Vals[rowData.attr_id as number] as string[])?.join(',')
        }
      }).then(res => {
        res.status === 200 ? MessageFunc('success', '更新成功') : MessageFunc('error', '更新失败')
      })
    },
    showInput: ($index: any) => { // 表格扩展框里添加数据 按钮点击事件
      inputStateArr.value[$index].inputValue = ''
      inputStateArr.value[$index].inputVisible = true

      nextTick(() => {
        saveTagInput.value?.focus()
      })
    }
  })

  // 标签页点击事件
  const handleClick = (tab: any) => {
    if (handleChangeVal.value) {
      dialogData.dialogTitle = tab.props.label
      activeName.value = tab.props.name
      store.dispatch('getIdCategories', { cid: handleChangeVal.value, sel: activeName.value }).then(() => {
        tableData.value = store.getters.CategorieToId(handleChangeVal.value, activeName.value)
        if (inputStateArr.value.length !== 0) inputStateArr.value = []
        tableData.value?.forEach((item) => {
          inputStateArr.value.push({inputVisible: false,inputValue: ''})
          input_Vals[item.attr_id as number] = toRaw(item).attr_vals as string[]
        })
      })
    } else {
      MessageFunc('error', '请选择商品')
      return
    }
  }

  return { tagInputObj, handleClick }
}